package com.cytanaa.youlike;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.facebook.android.*;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.Facebook.*;
import com.cytangaa.customhttpclient.CustomHttpClient;
import com.cytangaa.display.CustomView;

public class Login extends CustomView {
	private static final String fb_id = "416965195026704";
	private Facebook facebook = new Facebook(fb_id);
	private SharedPreferences mPrefs;
	private AsyncFacebookRunner mAsyncRunner;
	public EditText searchTarget;
	public static final String searchTextStart = "http://gdata.youtube.com/feeds/api/videos/-/";
	public static final String searchTextMid = "?v=2&format=1&start-index=";
	public static final String searchTextMid2 = "&max-results=10&orderby=";
	public static final String searchTextEnd = "&alt=jsonc";
	public static final String searchOr = "%7C";
	public static final String searchExOr = "-";
	public static final String nl = System.getProperty("line.separator");
	public static final String space = " ";
	public static String page = "1";
	public static String keywords = "";
	public static String order = "relevance";
	public static final String likeLink = "http://www.facebook.com/plugins/like.php?href="
			+ "http://www.facebook.com/YouLikePage";
	public static final String likeLink2 = "http://www.facebook.com/YouLikePage";
	public static final String photoLink = "http://www.freeimagehosting.net/t/fi8ps.jpg";
	// defined searching text for custom server
	public static String recommendedSearchStart = "http://youlike.knowithk.com/AddGetVideo.php?page=";
	public static String recommendedSearchEnd = "&category=";

	public static String typeOfVideo = "VideoList";

	private ProgressDialog pd = null;
	private Button recmd_btn, my_pref_btn, logout_btn1, recorded;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		// this.titlebar_title.setText("YouLike");
		Log.v("in login", "first created");
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		int height = displaymetrics.heightPixels;
		int width = displaymetrics.widthPixels;

		recmd_btn = (Button) findViewById(R.id.recmd_btn);
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
				width, height / 4);
		recmd_btn.setLayoutParams(layoutParams);

		my_pref_btn = (Button) findViewById(R.id.my_pref_btn);
		RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(
				width / 2, height / 2);
		layoutParams2.addRule(RelativeLayout.BELOW, R.id.recmd_btn);
		my_pref_btn.setLayoutParams(layoutParams2);

		logout_btn1 = (Button) findViewById(R.id.logout_btn1);
		RelativeLayout.LayoutParams layoutParams3 = new RelativeLayout.LayoutParams(
				width / 2, height / 4);
		layoutParams3.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.my_pref_btn);
		layoutParams3.addRule(RelativeLayout.RIGHT_OF, R.id.my_pref_btn);
		logout_btn1.setLayoutParams(layoutParams3);

		recorded = (Button) findViewById(R.id.recorded);
		RelativeLayout.LayoutParams layoutParams4 = new RelativeLayout.LayoutParams(
				width / 2, height / 4);
		layoutParams4.addRule(RelativeLayout.ALIGN_TOP, R.id.my_pref_btn);
		layoutParams4.addRule(RelativeLayout.RIGHT_OF, R.id.my_pref_btn);

		recorded.setLayoutParams(layoutParams4);

		searchTarget = (EditText) findViewById(R.id.search_edt_text);
		searchTarget.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// If the event is a key-down event on the "enter" button
				if ((event.getAction() == KeyEvent.ACTION_DOWN)
						&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
					// Perform action on key press
					Search(v);
					return true;
				}
				return false;
			}
		});

		/*
		 * Get existing access_token if any
		 */
		mPrefs = getSharedPreferences("facebook_session",
				MODE_PRIVATE);
		String access_token = mPrefs.getString("access_token", null);
		long expires = mPrefs.getLong("access_expires", 0);
		order = mPrefs.getString("order", "relevance");
		if (access_token != null) {
			facebook.setAccessToken(access_token);
			Log.i("access_token",
					"facebook.setAccessToken(access_token), and access_token=="
							+ access_token);

		}
		if (expires != 0) {
			Log.i("expires",
					"facebook.setAccessToken(access_token), and expires=="
							+ expires);
			facebook.setAccessExpires(expires);
		}

		/*
		 * Only call authorize if the access_token has expired.
		 */

		if (!facebook.isSessionValid()) {
			Log.v("in !facebook.isSessionValid()", "no pref");

			facebook.authorize(this,
					new String[] { "email", "publish_checkins" },
					new DialogListener() {
						@Override
						public void onComplete(Bundle values) {
							Log.v("facebook.authorize", "no pref");
							Log.v("!facebook.isSessionValid()",
									"mFacebook.getAccessToken(): "
											+ facebook.getAccessToken());
							Log.v("!facebook.isSessionValid()",
									"mFacebook.getAccessExpires(): "
											+ facebook.getAccessExpires());

							SharedPreferences mPrefs = getSharedPreferences(
									"facebook_session", MODE_PRIVATE);
							SharedPreferences.Editor editor = mPrefs.edit();
							editor.putString("access_token",
									facebook.getAccessToken());
							editor.putLong("access_expires",
									facebook.getAccessExpires());
							editor.commit();

						}

						@Override
						public void onFacebookError(FacebookError e) {
							Log.v("facebook.authorize",
									"mFacebook.onFacebookError(): " + e);
						}

						@Override
						public void onError(DialogError e) {
							Log.v("facebook.authorize",
									"mFacebook.onFacebookError(): " + e);
							Log.v("facebook.authorize", "mFacebook.onError(): "
									+ facebook.getAccessToken());
						}

						@Override
						public void onCancel() {
							Toast.makeText(
									getApplicationContext(),
									"You must be registered and signed in to perform that action",
									Toast.LENGTH_LONG).show();
							// finish();
							// onCancel, leaving the app
						}
					});
		}// end of pref check

	}

	public void Logout(View view) {

		clearPref();
		SharedPreferences checkprefs = getSharedPreferences("facebook_session",
				MODE_PRIVATE);
		String access_token = checkprefs.getString("access_token", null);
		Log.i("access_token",
				"mPrefs.getString(access_token, null), and access_token=="
						+ access_token);
		Log.i("access_token",
				"mPrefs.getString(access_token, null), and access_token=="
						+ access_token);

		mAsyncRunner = new AsyncFacebookRunner(facebook); // initialize
															// AsyncRunner, make
															// sure it's not
															// null
		mAsyncRunner.logout(Login.this, new RequestListener() {
			@Override
			public void onComplete(String response, Object state) {
				finish();
			}

			@Override
			public void onIOException(IOException e, Object state) {
			}

			@Override
			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
			}

			@Override
			public void onMalformedURLException(MalformedURLException e,
					Object state) {
			}

			@Override
			public void onFacebookError(FacebookError e, Object state) {
			}
		});
	}

	public void WatchBasket(View view) {
		Intent myIntent = new Intent(Login.this, RecordList.class);
		startActivity(myIntent);

	}

	public void Recommended(View view) {
		String searchText;
		String page = "0";
		searchText = recommendedSearchStart + page + recommendedSearchEnd;

		typeOfVideo = "Recommended";

		if (searchText == null || searchText == "") {
			Toast.makeText(Login.this, "Please enter at least one keyword",
					Toast.LENGTH_LONG).show();
		} else {
			// keywords = searchText;
			// try {
			// SharedPreferences mPrefs = getSharedPreferences(
			// "facebook_session", MODE_PRIVATE);
			// order = mPrefs.getString("order", "relevance");
			// // AsyncTask code here
			// String SearchLink = searchText;
			// new DownloadFromCustomServer().execute(SearchLink);
			// Log.v("Search checking ", SearchLink);
			// } catch (Exception ex) {
			// // your timeout code
			// Toast.makeText(this, "Network problem!", Toast.LENGTH_LONG)
			// .show();
			// }
			// this.pd = ProgressDialog.show(this, "Working..", "Searching...",
			// true, false);
			Intent myIntent = new Intent(Login.this,
					FragmentRecommendedList.class);

			Log.v("Check point! ready to star intent: ", "1");
			Log.v("Check point! ready to star intent: ", "0");
			// startActivity(myIntent);

			// Intent myIntent = new Intent(Login.this,
			// RecommendedFragment.class);
			startActivity(myIntent);
		}

	}

	public void WatchInterested(View view) {
		String categorySearchStart = "https://gdata.youtube.com/feeds/api/standardfeeds/";// add
																							// counrty
		String categorySearchMid = "/recently_featured_";// add category
		String categorySearchEnd = "/?v=2&format=1&start-index=1"
				+ "&max-results=10&alt=jsonc";
		SharedPreferences mPrefs = getSharedPreferences("facebook_session",
				MODE_PRIVATE);
		String country = mPrefs.getString("country_code", "US");
		String category = mPrefs.getString("category", "Comedy");
		typeOfVideo = category;
		Log.v("In interested", "typeOfVideo = " + typeOfVideo);

		String categorySearch = categorySearchStart + country
				+ categorySearchMid + category + categorySearchEnd;
		try {
			// AsyncTask code here
			new DownloadTask().execute(categorySearch);
			Log.v("Search checking ", categorySearch);
		} catch (Exception ex) {
			// your timeout code
			Toast.makeText(this, "Network problem!", Toast.LENGTH_LONG).show();
		}
		this.pd = ProgressDialog.show(this, "Working..", "Searching...", true,
				true);

	}

	public void Search(View view) {
		String searchText;
		typeOfVideo = "Search";
		searchText = searchTarget.getText().toString();
		if (searchText == null || searchText.equalsIgnoreCase("")) {
			Toast.makeText(Login.this, "Please enter at least one keyword",
					Toast.LENGTH_LONG).show();
		} else if (Character.isWhitespace(searchText.charAt(0))) {
			// do something
			searchText = searchText.replaceFirst(space, "");
		}

		searchText = searchText.replaceAll(space, searchOr);
		if (searchText == null || searchText == "") {
			Toast.makeText(Login.this, "Please enter at least one keyword",
					Toast.LENGTH_LONG).show();
		} else {
			keywords = searchText;
			try {
				SharedPreferences mPrefs = getSharedPreferences(
						"facebook_session", MODE_PRIVATE);
				order = mPrefs.getString("order", "relevance");
				// AsyncTask code here
				String SearchLink = searchTextStart + searchText
						+ searchTextMid + page + searchTextMid2 + order
						+ searchTextEnd;
				new DownloadTask().execute(SearchLink);
				Log.v("Search checking ", SearchLink);
			} catch (Exception ex) {
				// your timeout code
				Toast.makeText(this, "No drivers found, network problem!",
						Toast.LENGTH_LONG).show();
			}
			this.pd = ProgressDialog.show(this, "Working..", "Searching...",
					true, true);
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		facebook.authorizeCallback(requestCode, resultCode, data);
		// Log.v("onActivityResult", "no pref");

	}

	public void clearPref() {
		SharedPreferences prefs = getSharedPreferences("facebook_session",
				MODE_PRIVATE);
		SharedPreferences.Editor editor = prefs.edit();
		editor.remove("access_token");
		editor.remove("access_expires");
		editor.commit();
	}

	/**
	 * The following is the AsyncTask behind the progress dialog pd
	 * 
	 * @author uney
	 * 
	 */

	private class DownloadTask extends AsyncTask<String, Void, Object> {
		// TODO This is for downloading data from YouTube data API

		protected Object doInBackground(String... args) {
			// This is where you would do all the work of downloading your data
			try {
				String a = "hello";

				for (String s : args) {
					a = s;
				}
				try {
					String response = null;
					Log.i("AsyncTask Downloading task", "The link:" + a);
					response = CustomHttpClient.executeHttpGet(a);
					Spanned tempres = Html.fromHtml(response);
					response = tempres.toString();
					String NL = System.getProperty("line.separator");
					response = response.replaceAll(NL, "");
					// String space=" ";
					// response= response.replaceAll(space,"");
					Log.v("Response: ", "res=" + response + "end");
					return response;
				} catch (Exception e) {
					e.printStackTrace();
					Toast.makeText(Login.this, "Network problem!",
							Toast.LENGTH_LONG).show();
					return 2;
				}
			} catch (Exception anyError) {
				return null;
			}

		}

		protected void onPostExecute(Object result) {


			Object data = result;

			if (Login.this.pd != null) {
				Login.this.pd.dismiss();
			}

			if (data != null) {
				int arrayCounter = 0;
				String[] videoInfo = new String[100];
				String response = String.valueOf(data);
				data = null;

				if (!response.equals("2")) {
					JSONObject jsonRaw;
					JSONArray jsonArray;
					try {
						jsonRaw = new JSONObject(response);
						JSONObject dataObject = jsonRaw.getJSONObject("data"); // this
																				// is
																				// the
																				// "data":
																				// {
																				// }
																				// part
						jsonArray = dataObject.getJSONArray("items");
						int counter = 0;
						for (int i = 0; i < (jsonArray.length()); i++) {
							JSONObject jsonObject = jsonArray.getJSONObject(i);
							videoInfo[counter] = jsonObject.getString("id");
							counter++;
							videoInfo[counter] = jsonObject
									.getString("uploaded");
							counter++;
							if (jsonObject.has("viewCount")) {
								// it has it, do appropriate processing
								videoInfo[counter] = jsonObject
										.getString("viewCount");
							} else {
								videoInfo[counter] = "0";
							}
							counter++;
							videoInfo[counter] = jsonObject.getString("title");
							counter++;
							videoInfo[counter] = jsonObject
									.getString("description");
							counter++;

							Log.v("check videoInfo, uploaded", videoInfo[0]);
							Log.v("check videoInfo, category", videoInfo[1]);
							Log.v("check videoInfo, title", videoInfo[2]);
							Log.v("check videoInfo, description", videoInfo[3]);

							JSONObject thumbnailObject = jsonObject
									.getJSONObject("thumbnail");
							videoInfo[counter] = thumbnailObject
									.getString("sqDefault");
							/*
							 * 
							 * 
							 * try { bitmap[i]=
							 * BitmapFactory.decodeStream((InputStream)new
							 * URL(videoInfo[counter]).getContent()); } catch
							 * (MalformedURLException e) { // TODO
							 * Auto-generated catch block e.printStackTrace(); }
							 * catch (IOException e) { // TODO Auto-generated
							 * catch block e.printStackTrace(); }
							 */
							counter++;
							JSONObject playerObject = jsonObject
									.getJSONObject("player");
							if (playerObject.has("default")) {
								// it has it, do appropriate processing
								videoInfo[counter] = playerObject
										.getString("default");

							} else {
								videoInfo[counter] = "nil";
							}
							counter++;
							Log.v("check videoInfo, thumbnail",
									thumbnailObject.getString("sqDefault"));
							Log.v("check videoInfo, thumbnail",
									thumbnailObject.getString("sqDefault"));
							JSONObject contentObject = jsonObject
									.getJSONObject("content");

							if (contentObject.has("5")) {
								// it has it, do appropriate processing
								videoInfo[counter] = contentObject
										.getString("5");

							} else {
								videoInfo[counter] = "nil";
							}
							counter++;
							if (contentObject.has("1")) {
								// it has it, do appropriate processing
								videoInfo[counter] = contentObject
										.getString("1");

							} else {
								videoInfo[counter] = "nil";
							}
							counter++;

							videoInfo[counter] = jsonObject
									.getString("duration");
							counter++;
							Log.v("check videoInfo, rtsp",
									contentObject.getString("1"));
							Log.v("check videoInfo, duration",
									jsonObject.getString("duration"));

							arrayCounter++;
						}
					} catch (JSONException e) {
						Toast.makeText(Login.this,
								R.string.connection_error_txt,
								Toast.LENGTH_LONG).show();
						e.printStackTrace();
					}

					int indexToList = 0;
					// int count = driverInfo.length;
					// if(driverInfo[0][0]!=null){
					Log.v("Check point! in if", "arrayCounter=" + arrayCounter
							+ ".");
					// TODO index changed
					indexToList = arrayCounter * 9;
					Log.v("Check point! in if", "indexToList=" + indexToList
							+ ".");
					Bundle bundle = new Bundle();
					bundle.putString("keywords", keywords);
					bundle.putStringArray("videoInfo", videoInfo);
					bundle.putInt("indexToList", indexToList);
					bundle.putString("typeOfVideo", typeOfVideo);
					// bundle.putParcelableArray("thumbnails", bitmap);

					Intent myIntent = new Intent(Login.this, VideoList.class);

					Log.v("Check point! ready to star intent: ", "1");
					myIntent.putExtras(bundle);
					Log.v("Check point! ready to star intent: ", "0");
					startActivity(myIntent);

				} else {
					Toast.makeText(Login.this, R.string.no_video_txt,
							Toast.LENGTH_LONG).show();

				}

			} else {
				Toast.makeText(Login.this, R.string.connection_error_txt,
						Toast.LENGTH_LONG).show();

			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		menu.add(Menu.NONE, Menu.FIRST + 1, 5, "Setting").setIcon(
				android.R.drawable.ic_menu_preferences);
		menu.add(Menu.NONE, Menu.FIRST + 2, 5, "Like us on Facebook").setIcon(
				R.drawable.like_menu);
		menu.add(Menu.NONE, Menu.FIRST + 3, 5, "Share the fun").setIcon(
				R.drawable.share_menu);

		return true;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case Menu.FIRST + 1:
			Intent i = new Intent(this, Preferences.class);
			startActivityForResult(i, 1);

			break;
		case Menu.FIRST + 2:
			// Intent i = new Intent(this, Preferences.class);
			Intent browserIntent2 = new Intent(Intent.ACTION_VIEW,
					Uri.parse(likeLink2));
			startActivity(browserIntent2);
			break;

		case Menu.FIRST + 3:
			// Intent i = new Intent(this, Preferences.class);
			postToWall();
			break;
		}
		return false;

	}
	
	
	/**
	 * Facebook sharing handler
	 */
	public void postToWall() {
		Bundle parameters = new Bundle();

		parameters.putString("message", "");
		parameters.putString("link", likeLink2);
		parameters.putString("description", "Good Stuff!!!!");
		parameters.putString("picture", photoLink);

		if (facebook.isSessionValid()) {
			Log.i("postToWall", "mFacebook.isSessionValid()");
			// mAsyncRunner.request("me/feed", parameters, "POST", new
			// FacebookPostListener(), null);

			facebook.dialog(this, "feed", parameters, new DialogListener() {
				@Override
				public void onFacebookError(FacebookError e) {
					Log.i("onFacebookError", "youtubeLink == " + e);

				}

				@Override
				public void onError(DialogError e) {
					Log.i("onFacebookError", "onCancel == " + e);

				}

				@Override
				public void onComplete(Bundle values) {
				}

				@Override
				public void onCancel() {

				}
			});

		} else {
			Log.i("postToWall", "mFacebook.isSessionValid() is not true");
			Log.i("postToWall",
					"mFacebook.getAccessToken(): " + facebook.getAccessToken());

			facebook.authorize(this,
					new String[] { "email", "publish_stream" },
					new DialogListener() {

						@Override
						public void onCancel() {
							// Function to handle cancel event
						}

						@Override
						public void onComplete(Bundle values) {
							// Function to handle complete event
							// Edit Preferences and update facebook acess_token
							SharedPreferences.Editor editor = mPrefs.edit();
							// mFacebook.setAccessToken("tooken");
							editor.putString("access_token",
									facebook.getAccessToken());
							editor.putLong("access_expires",
									facebook.getAccessExpires());
							editor.commit();
							Log.i("postToWall", "mFacebook.getAccessToken(): "
									+ facebook.getAccessToken());
							Log.i("postToWall",
									"mFacebook.getAccessExpires(): "
											+ facebook.getAccessExpires());
						}

						@Override
						public void onError(DialogError error) {
							// Function to handle error
							Log.i("postToWall", "mFacebook.onError(): " + error);

						}

						@Override
						public void onFacebookError(FacebookError fberror) {
							// Function to handle Facebook errors
							Log.i("postToWall", "mFacebook.onFacebookError(): "
									+ fberror);
						}

					});
		}

	}

}
